<template>
  <view class="register-container">
    <!-- 顶部背景 -->
    <view class="register-background"></view>

    <!-- 注册卡片 -->
    <view class="register-card">
      <view class="register-title">渠道注册</view>

      <!-- 注册表单 -->
      <view class="register-form">
        <!-- 手机号输入 -->
        <view class="form-item">
          <text class="iconfont icon-shouji"></text>
          <input
            type="number"
            v-model="phone"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>
        <view class="input-error" v-if="phoneError">{{ phoneError }}</view>

        <!-- 验证码输入 -->
        <view class="form-item verification-code">
          <text class="iconfont icon-yanzhengma"></text>
          <input
            type="number"
            v-model="verificationCode"
            placeholder="请输入验证码"
            maxlength="6"
          />
          <view
            class="get-code-btn"
            :class="{ disabled: !canSendCode || countdown > 0 || isSendingCode }"
            @click="getVerificationCode"
          >
            <text v-if="isSendingCode" class="loading-icon"></text>
            <text v-else>{{ countdown > 0 ? `${countdown}s` : "获取验证码" }}</text>
          </view>
        </view>
        <view class="input-error" v-if="codeError">{{ codeError }}</view>

        <!-- 渠道名称输入 -->
        <view class="form-item">
          <text class="iconfont icon-qudaomingcheng"></text>
          <input type="text" v-model="channelName" placeholder="请输入渠道名称" />
        </view>
        <view class="input-error" v-if="nameError">{{ nameError }}</view>

        <!-- 渠道描述输入 -->
        <view class="form-item">
          <text class="iconfont icon-miaoshu"></text>
          <input type="text" v-model="description" placeholder="请输入渠道描述（选填）" />
        </view>

        <!-- 密码输入 -->
        <view class="form-item">
          <text class="iconfont icon-mima"></text>
          <input
            v-if="showPassword"
            type="text"
            v-model="password"
            placeholder="请输入密码"
            maxlength="20"
          />
          <input
            v-if="!showPassword"
            type="password"
            v-model="password"
            placeholder="请输入密码"
            maxlength="20"
            :password="true"
          />
          <text
            class="iconfont"
            :class="showPassword ? 'icon-xianshimima' : 'icon-buxianshimima'"
            @click="togglePasswordVisibility('password')"
            style="padding: 0 0 0 20px"
          ></text>
        </view>
        <view class="password-tips">密码长度为6-20位，可以是数字或字母与数字组合</view>
        <view class="input-error" v-if="passwordError">{{ passwordError }}</view>

        <!-- 确认密码输入 -->
        <view class="form-item">
          <text class="iconfont icon-mima"></text>
          <input
            v-if="showConfirmPassword"
            type="text"
            v-model="confirmPassword"
            placeholder="请再次输入密码"
            maxlength="20"
          />
          <input
            v-if="!showConfirmPassword"
            type="password"
            v-model="confirmPassword"
            placeholder="请再次输入密码"
            maxlength="20"
            :password="true"
          />
          <text
            class="iconfont"
            :class="showConfirmPassword ? 'icon-xianshimima' : 'icon-buxianshimima'"
            @click="togglePasswordVisibility('confirm')"
            style="padding: 0 0 0 20px"
          ></text>
        </view>
        <view class="input-error" v-if="confirmError">{{ confirmError }}</view>
      </view>

      <!-- 注册按钮 -->
      <view
        class="register-btn"
        :class="{ disabled: !isFormValid || isSubmitting }"
        @click="register"
      >
        <text v-if="!isSubmitting">注册</text>
        <text v-else class="loading-spinner"></text>
      </view>

      <!-- 已有账号，去登录 -->
      <view class="login-link">
        <text @click="goToLogin">已有账号？立即登录</text>
      </view>
    </view>

    <!-- 底部文本 -->
    <view class="register-footer">沃客薪服 · 渠道服务平台</view>
  </view>
</template>

<script>
export default {
  name: "RegisterPage",
  data() {
    return {
      phone: "",
      verificationCode: "",
      channelName: "",
      description: "",
      password: "",
      confirmPassword: "",
      showPassword: false,
      showConfirmPassword: false,
      countdown: 0,
      timer: null,
      isSubmitting: false,
      isSendingCode: false, // 发送验证码状态标记

      // 错误信息
      phoneError: "",
      codeError: "",
      nameError: "",
      passwordError: "",
      confirmError: "",
    };
  },
  computed: {
    canSendCode() {
      // 验证手机号格式是否正确
      return this.validatePhone(this.phone);
    },
    isFormValid() {
      // 表单验证规则
      return (
        this.validatePhone(this.phone) &&
        this.verificationCode.length === 6 &&
        this.channelName.length > 0 &&
        this.validatePassword(this.password) &&
        this.password === this.confirmPassword
      );
    },
  },
  beforeDestroy() {
    // 清除定时器
    this.clearCountdownTimer();
  },
  methods: {
    // 新增方法：切换密码可见性
    togglePasswordVisibility(field) {
      if (field === "password") {
        this.showPassword = !this.showPassword;
      } else if (field === "confirm") {
        this.showConfirmPassword = !this.showConfirmPassword;
      }
    },
    validatePhone(phone) {
      // 验证手机号格式
      return /^1[3-9]\d{9}$/.test(phone);
    },
    validatePassword(password) {
      // 验证密码规则：6-20位，可以是数字或字母或字母与数字组合
      return /^[A-Za-z0-9]{6,20}$/.test(password);
    },
    clearCountdownTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    getVerificationCode() {
      // 重置错误信息
      this.phoneError = "";
      this.codeError = "";

      if (!this.canSendCode || this.countdown > 0 || this.isSendingCode) {
        return;
      }

      // 验证手机号
      if (!this.validatePhone(this.phone)) {
        this.phoneError = "请输入正确的手机号";
        return;
      }

      // 设置发送状态为true
      this.isSendingCode = true;

      // 发送请求
      this.$request.getSmsCode(
        {
          mobile: this.phone,
          scenario: "2", // 1员工注册登录 2渠道注册登录 3发薪确认 4变更员工手机号 5变更渠道手机号 6渠道忘记密码
        },
        (res) => {
          // this.formData.smsToken = res.sms_token;

          // 提示成功
          uni.showToast({
            title: "验证码已发送",
            icon: "success",
          });

          // 开始倒计时
          this.startCountdown();
        },
        () => {
          uni.showToast({
            title: "网络异常，请稍后重试",
            icon: "none",
          });
        },
        () => {
          // 重置发送状态
          this.isSendingCode = false;
        }
      );
    },
    startCountdown() {
      this.countdown = 60;
      this.clearCountdownTimer(); // 先清除可能存在的定时器

      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          this.clearCountdownTimer();
        }
      }, 1000);
    },
    validateForm() {
      // 重置所有错误信息
      this.phoneError = "";
      this.codeError = "";
      this.nameError = "";
      this.passwordError = "";
      this.confirmError = "";

      let isValid = true;

      // 验证手机号
      if (!this.phone) {
        this.phoneError = "请输入手机号";
        isValid = false;
      } else if (!this.validatePhone(this.phone)) {
        this.phoneError = "请输入正确的手机号";
        isValid = false;
      }

      // 验证验证码
      if (!this.verificationCode) {
        this.codeError = "请输入验证码";
        isValid = false;
      } else if (this.verificationCode.length !== 6) {
        this.codeError = "请输入6位验证码";
        isValid = false;
      }

      // 验证渠道名称
      if (!this.channelName) {
        this.nameError = "请输入渠道名称";
        isValid = false;
      }

      // 验证密码
      if (!this.password) {
        this.passwordError = "请输入密码";
        isValid = false;
      } else if (!this.validatePassword(this.password)) {
        this.passwordError = "密码不符合要求";
        isValid = false;
      }

      // 验证确认密码
      if (!this.confirmPassword) {
        this.confirmError = "请确认密码";
        isValid = false;
      } else if (this.password !== this.confirmPassword) {
        this.confirmError = "两次输入的密码不一致";
        isValid = false;
      }

      return isValid;
    },
    register() {
      if (!this.validateForm()) {
        return;
      }

      // 显示加载中
      this.isSubmitting = true;
      uni.showLoading({
        title: "注册中...",
        mask: true,
      });

      // 提交注册请求
      this.submitRegister();
    },
    submitRegister() {
      // 调用注册接口
      this.$request.register(
        {
          mobile: this.phone,
          verify_code: this.verificationCode,
          password: this.password,
          confirm_password: this.confirmPassword,
          name: this.channelName,
          description: this.description || "", // 选填项
        },
        (res) => {
          // 隐藏加载中
          uni.hideLoading();
          this.isSubmitting = false;

          // 注册成功
          uni.showToast({
            title: "注册成功",
            icon: "success",
          });

          // 延迟跳转到登录页面
          setTimeout(() => {
            this.goToLogin();
          }, 1500);
        },
        (err) => {
          // 隐藏加载中
          uni.hideLoading();
          this.isSubmitting = false;
        }
      );
    },
    goToLogin() {
      // 跳转到登录页面
      uni.navigateTo({
        url: "/pages/login",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/static/scss/variables.scss";
.register-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f5f5f5;
  position: relative;

  /* 顶部背景 */
  .register-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 400rpx;
    background: linear-gradient(to bottom, $colorPrimary, $colorPrimaryLight);
    border-radius: 0 0 50% 50% / 0 0 20% 20%;
    z-index: 1;
  }

  /* 注册卡片 */
  .register-card {
    position: relative;
    width: 90%;
    margin-top: 180rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.1);
    padding: 60rpx 40rpx;
    z-index: 2;

    .register-title {
      font-size: 48rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 60rpx;
    }

    /* 表单样式 */
    .register-form {
      margin-bottom: 60rpx;

      .form-item {
        display: flex;
        align-items: center;
        height: 90rpx;
        border-bottom: 1rpx solid #eee;
        margin-bottom: 20rpx;

        .iconfont {
          font-size: 40rpx;
          color: $colorPrimary;
          margin-right: 20rpx;
        }

        input {
          flex: 1;
          height: 100%;
          font-size: 28rpx;
        }
      }

      /* 验证码输入框样式 */
      .verification-code {
        position: relative;

        .get-code-btn {
          width: 200rpx;
          height: 70rpx;
          line-height: 70rpx;
          text-align: center;
          color: #fff;
          font-size: 24rpx;
          background-color: $colorPrimary;
          border-radius: 35rpx;
          display: flex;
          justify-content: center;
          align-items: center;

          .loading-icon {
            display: inline-block;
            width: 30rpx;
            height: 30rpx;
            border: 2rpx solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 0.8s linear infinite;
          }

          &.disabled {
            background-color: #ccc;
          }
        }
      }

      .password-tips {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
        padding-left: 60rpx;
      }

      .input-error {
        font-size: 24rpx;
        color: #ff3b30;
        margin: -10rpx 0 20rpx;
        padding-left: 60rpx;
      }
    }

    /* 注册按钮 */
    .register-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      text-align: center;
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
      background-color: $colorPrimary;
      border-radius: 45rpx;
      margin-bottom: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;

      &.disabled {
        background-color: #ccc;
      }

      .loading-spinner {
        display: inline-block;
        width: 30rpx;
        height: 30rpx;
        border: 3rpx solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: #fff;
        animation: spin 0.8s linear infinite;
      }
    }

    /* 登录链接 */
    .login-link {
      text-align: center;
      font-size: 26rpx;
      color: $colorPrimary;

      text {
        padding: 10rpx;
      }
    }
  }

  /* 底部文本 */
  .register-footer {
    position: fixed;
    bottom: 60rpx;
    font-size: 24rpx;
    color: #999;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
